<?php

namespace Admin\Controller;

use Think\Controller;

class LoginController extends Controller
{

    /**
     * 显示登录页面
     */
    public function login()
    {
        $this->display();
    }


    /**
     *
     * 验证码生成
     */
    public function verify_c()
    {
        $Verify = new \Think\Verify();
        $Verify->fontSize = 18;
        $Verify->length = 4;
        $Verify->useNoise = false;
        $Verify->codeSet = '0123456789';
        $Verify->imageW = 130;
        $Verify->imageH = 50;
        $Verify->entry();
    }

    /**
     * 验证码检查
     */
    function check_verify($code)
    {

        $Verify = new \Think\Verify();

        return $Verify->check($code);
    }

    /**
     * 进行登录处理
     */
    public function login_do()
    {
        $username = trim($_POST['username']);
        $password = trim($_POST['password']);
        $code = trim($_POST['code']);

        if (empty($username)) {
            $this->error('用户名不能为空！');
        }
        if (empty($password)) {
            $this->error('密码不能为空！');
        }
        // 检查验证码
        if (!$this->check_verify($code)) {

            $this->error("亲，验证码输错了哦！");
        }

        $result = M('admin')->where(array('username' => $username))->find();

        if ($result) {
            if (md5($password) == $result['password']) {

                //将管理员信息存入session
                session('admin_name', $username);
                session('uid', $result['id']);
                $this->success('登录成功！！', U('index/index'), true);

            } else {
                $this->error('密码错误,请重新输入！');
            }
        } else {
            $this->error('用户名不存在，请重新输入！');
        }
    }

    /**
     * 退出登录处理
     */
    public function logout()
    {
        //清空session
        session('admin_name', null);
        $this->redirect('/Admin/Login/login');

    }

}